package com.zheng.admin.web;

import com.alibaba.druid.util.StringUtils;
import com.zheng.admin.common.Consts;
import com.zheng.admin.dto.AdminResp;
import com.zheng.admin.entity.PermSubject;
import com.zheng.admin.form.LoginUser;
import com.zheng.admin.model.User;
import com.zheng.admin.service.UserService;
import com.zheng.admin.utils.PasswordUtils;
import com.zheng.admin.validator.LoginUserValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by zcz on 2017/10/25.
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private LoginUserValidator loginUserValidator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(loginUserValidator);
    }

    @RequestMapping(value = "/login.html")
    public String login(Model model) {
        return "login";
    }

    @ResponseBody
    @RequestMapping(value = "/doLogin.do")
    public AdminResp doLogin(@ModelAttribute("loginUser") @Validated LoginUser loginUser, BindingResult result, Model model,
                             HttpServletRequest request, HttpServletResponse response) {
        if (result.hasErrors()) {
            ObjectError objectError = result.getAllErrors().get(0);
            return new AdminResp(objectError.getCode(), objectError.getDefaultMessage());
        }

        User user = userService.getUserByPhone(loginUser.getPhone());
        if (user == null) {
            return new AdminResp("user.not.exists", "用户不存在");
        }
        if (!StringUtils.equals(user.getStatus(), "normal")) {
            return new AdminResp("user.disabled", "用户状态异常");
        }

        if (!PasswordUtils.checkPass(loginUser.getPassword(), user.getPassword())) {
            return new AdminResp("user.password.wrong", "密码错误");
        }

        //登录成功，保存session。
        PermSubject permSubject = userService.buildUserPermSubject(user.getId());
        HttpSession session = request.getSession(true);
        session.setAttribute(Consts.SESS_USER_ID, user.getId());
        session.setAttribute(Consts.SESS_PERM_SUB, permSubject);

        return AdminResp.SUCCESS_RESP;
    }
}
